<template>
  <div id="echartsBox" style="height: 36vh"></div>
</template>
<script lang="ts">
import * as echarts from 'echarts';
import { defineComponent, onMounted, Ref, ref, watch } from 'vue';
import { getErrorLianluNumberApi } from '@/utils/errorLianlu';

type EChartsOPtion = echarts.EChartsOption;

interface ErrorLianluNumberDto {
  record_date: string
  number: number
}
interface ResultDto {
  code: number
  data: Array<ErrorLianluNumberDto>
  message: string
}
type QueryDateDto = [string, string]

export default defineComponent({
  components: {},
  props: ['queryTime'],
  setup(props) {
    // 搜索的时间范围
    let queryDate: Ref<QueryDateDto> = ref(['', ''] as [string, string]);
    let echartDataX: Ref<string[]> = ref([]);
    let echartDataY: Ref<number[]> = ref([]);
    // 保存后端返回的所有异常链路信息的时间及异常条数
    let allErrorlianluNumber: Ref<ErrorLianluNumberDto[]> = ref([]);

    // 颜色列表
    // const colorList = ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622'];
    // echarts容器
    let echartsDom: HTMLElement;
    // 初始化echarts
    let myChart: echarts.ECharts;

    let option: EChartsOPtion = {
      xAxis: {
        name: '日期',
        type: 'category',
        data: echartDataX.value
      },
      yAxis: {
        name: '异常数量',
        type: 'value'
      },
      series: [
        {
          data: echartDataY.value,
          type: 'bar',
          label: {
            show: true,
            position: 'top'
          },
          color: '#61a0a8'
        },
        {
          type: 'line',
          data: echartDataY.value,
          smooth: true,
          color: '#91c7ae'
        }
      ]
    }


    // 画echarts图
    function drawEchart() {
      echartsDom = document.querySelector('#echartsBox') as HTMLElement;
      myChart = echarts.init(echartsDom);
      // 绘制echarts图
      option && myChart.setOption(option);
    }
    // 当props值发生改变时，即选择时间发生改变时
    function onChangeQueryDate() {
      console.log(props.queryTime);
      // 重新赋值查询日期
      queryDate.value[0] = props.queryTime[0];
      queryDate.value[1] = props.queryTime[1];
      console.log(queryDate);
      initErrorNumberData(queryDate.value)
    }
    // 根据选择日期设置dataX、dataY
    async function initErrorNumberData(queryDate?: [string, string]) {
      // 初始化echarts数据
      echartDataX.value.length = 0;
      echartDataY.value.length = 0;
      // 定义一个表示判断是否有传入查询日期，或者查询日期是否为空
      const haveQueryDate = !queryDate ? false : queryDate[0] ? true : false;

      if (!haveQueryDate) {
        // 如果没有查询日期或者查询日期是空
        // 获取当前日期的时间戳
        let todayDateTime = new Date(new Date().toLocaleDateString()).getTime();
        //  默认开始时间为当前时间的前30天
        let startDataTime = todayDateTime - 2592000000;
        // 从当前日期减30之后每次循环加一天的时间
        while (startDataTime < todayDateTime) {
          // 时间戳加上一天的事件戳
          startDataTime += 86400000;
          // 给坐标轴数据分别重新赋值
          echartDataX.value.push(new Date(startDataTime).toLocaleDateString().slice(5));
          echartDataY.value.push(0);
        }
      } else {
        // 查询日期不为空，则统计日期为查询日期期间
        // 开始日期时间戳
        let startDataTime = new Date(new Date((queryDate as [string, string])[0]).toLocaleDateString()).getTime()
        console.log('startTime', new Date(startDataTime).toLocaleString());
        // 结束日期时间戳
        let endDateTime = new Date(new Date((queryDate as [string, string])[1]).toLocaleDateString()).getTime();
        while (startDataTime <= endDateTime) {
          // 给坐标轴数据分别重新赋值
          echartDataX.value.push(new Date(startDataTime).toLocaleDateString().slice(5));
          echartDataY.value.push(0);
          // 时间戳加上一天的事件戳
          startDataTime += 86400000;
        }
      }
      // 重新赋值echartsDataY的数据
      setEchartsLianluDataY();

      // 重新加载echarts图
      console.log('重新画echarts图', myChart);
      myChart.setOption(option);
    }
    // 将时间内的异常链路数量赋值给y轴数据
    function setEchartsLianluDataY() {
      allErrorlianluNumber.value.forEach(item => {
        const itemDateStr = new Date(item.record_date).toLocaleDateString().slice(5);
        const dataXIndex = echartDataX.value.indexOf(itemDateStr);
        if (dataXIndex !== -1) {
          echartDataY.value[dataXIndex] = Number(item.number);
        }
      })
    }
    // 获取所有的异常链路信息及数量
    async function getAllErrorLianluNumber() {
      await getErrorLianluNumberApi().then(res => {
        const result = res as unknown as ResultDto;
        if (result.code === 200) {
          allErrorlianluNumber.value.push(...result.data);
        }
        console.log('链路异常数量', allErrorlianluNumber);
      })
    }
    onMounted(async () => {
      await getAllErrorLianluNumber();
      drawEchart();
      initErrorNumberData();
    });
    watch(props, () => {
      onChangeQueryDate();
    }, { deep: true });
    return { queryDate, echartDataX };
  },
});
</script>

<style scoped>
</style>
